import { toast } from "sonner";
import { useCallback, useEffect, useRef } from "react";
import useChatStore from "@/store/chat";
import UserMessage from "./UserMessage";
import { request } from "@/lib/utils/request";
import ResponseMessage from "./ResponseMessage";
import useLatestRef from "@/lib/hooks/useLatestRef";
import { IResponseMessage, IUserMessage, Message } from "@/lib/types";
import { apiHost } from "@/lib/constants";

type MessagesProps = {
  isAnswering: boolean;
  onEdit: (content: string, parent: string | null) => void;
  onClickRecommend: (prompt: string) => void;
  onRegenerate: (parent: string) => void;
};

export default function Messages(props: MessagesProps) {
  const { onEdit, onClickRecommend, onRegenerate } = props;
  const messages = useChatStore((state) => state.messages);
  const appendMessage = useChatStore((state) => state.appendMessage);
  const scrollableRef = useRef<HTMLDivElement>(null);
  const messagesRef = useLatestRef(messages);
  const handleResponseFeedback = useCallback(
    async (
      rating: 0 | 1,
      describe: string,
      message: Message<IResponseMessage>,
    ) => {
      const userMessage = messagesRef.current.find(
        (m) => m.id === message.parent,
      );
      const res = await request<{ code: number }>(`${apiHost}/zs/feedback`, {
        method: "put",
        data: {
          rating,
          describe,
          timestamp: Date.now(),
          query: userMessage?.message.content,
          answer: message.message.content,
        },
      });
      if (res.code === 200) {
        toast.success("提交成功");
      } else {
        throw res;
      }
    },
    [], // eslint-disable-line react-hooks/exhaustive-deps
  );

  useEffect(() => {
    let timer: ReturnType<typeof setTimeout>;
    if (messages.length === 0) {
      timer = setTimeout(() => {
        appendMessage({
          id: "preset-assistant-message",
          role: "assistant",
          content:
            "你好，我是云瀚知识库助手。你可以问我问题，了解智慧图书馆技术应用联盟（即云瀚联盟）。",
          recommend: [
            "云瀚联盟是什么？",
            "云瀚平台的核心优势有哪些？",
            "如何加入云瀚联盟？",
          ],
          source: [],
          done: true,
          timestamp: Date.now(),
        });
      }, 10);
    }

    if (scrollableRef.current) {
      scrollableRef.current.scroll({
        top: scrollableRef.current.scrollHeight,
        behavior: "smooth",
      });
    }

    return () => {
      if (typeof timer !== "undefined") {
        clearTimeout(timer);
      }
    };
  }, [messages, appendMessage]);

  return (
    <div
      ref={scrollableRef}
      className="relative flex min-h-0 flex-auto flex-col overflow-auto text-[#F7F7F7]"
    >
      {messages.map((message) => {
        if (message.message.role === "user") {
          return (
            <UserMessage
              key={message.id}
              message={message as Message<IUserMessage>}
              onEditConfirm={onEdit}
            />
          );
        }
        return (
          <ResponseMessage
            key={message.id}
            message={message as Message<IResponseMessage>}
            onSendFeedback={handleResponseFeedback}
            onClickRecommend={onClickRecommend}
            onRegenerate={onRegenerate}
          />
        );
      })}
    </div>
  );
}

function isUserMessage(message: Message): message is Message<IUserMessage> {
  return message.message.role === "user";
}
